package domain

import (
	"github.com/lab-online/internal/shared/code"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/pkg/resp"
)

func (d *Domain) RefreshToken(refreshToken string) (string, error) {
	if claims, err := d.jwt.ParseToken(refreshToken); err != nil || claims.Role != 0 {
		return "", resp.RESTErrAuth
	} else {
		user, dbErr := d.repository.GetUserByUsername(claims.Username)
		if dbErr != nil {
			return "", code.ErrorPicker(
				dbErr, code.DatabaseUserNotFound, constant.RESTErrUserNotFound,
			)
		}

		if token, err := d.jwt.GenToken(user.GetUsername(), user.GetRole()); err != nil {
			return "", constant.RESTErrTokenGenError
		} else {
			return token, nil
		}
	}
}
